package com.skyblue.statemachine.forkjoin;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.config.StateMachineBuilder;
import org.springframework.stereotype.Component;

@Component
public class ForkJoinStateMachineBuilder {

    private final static String MACHINE_ID = "fjMachine";

    public StateMachine<String, String> build(BeanFactory beanFactory) throws Exception {
        StateMachineBuilder.Builder<String, String> builder = StateMachineBuilder.builder();

        builder.configureConfiguration()
                .withConfiguration()
                .machineId(MACHINE_ID)
                .beanFactory(beanFactory);

        builder.configureStates()
                .withStates()
                .initial("初始状态-0")
                .fork("分支状态-0")
                .join("合并状态-0")
                .and().withStates()
                .parent("分支状态-0")
                .initial("分支状态-0-1")
                .end("合并状态-0")
                .and().withStates()
                .parent("分支状态-0")
                .initial("分支状态-0-2")
                .end("合并状态-0");

        builder.configureTransitions()
                .withFork()
                .source("分支状态-0")
                .target("分支状态-0-1")
                .target("分支状态-0-2")
                .and()
                .withJoin()
                .source("分支状态-0-1")
                .source("分支状态-0-2")
                .target("合并状态-0");

        builder.configureTransitions()
                .withExternal()
                .source("初始状态-0")
                .target("分支状态-0")
                .event("事件-0");
//                .and().withExternal()
//                .source("分支状态-0")
//                .target("分支状态-0-1")
//                .event("事件-0-1")
//                .and().withExternal()
//                .source("分支状态-0")
//                .target("分支状态-0-2")
//                .event("事件-0-2")
//                .and().withExternal()
//                .source("分支状态-0-1")
//                .target("合并状态-0")
//                .event("事件-1-0")
//                .and().withExternal()
//                .source("分支状态-0-2")
//                .target("合并状态-0")
//                .event("事件-2-0");

        return builder.build();
    }

}